package net.xo68.destiny.manager.eventHandle;

import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.report.DatagramSerializer;
import net.xo68.destiny.contract.domain.report.JobHandleReplyDatagram;
import net.xo68.destiny.contract.enums.handler.JobHandleStateEnum;
import net.xo68.destiny.contract.enums.job.JobInstanceExtendEnum;
import net.xo68.destiny.contract.enums.job.JobInstanceStateEnum;
import net.xo68.destiny.core.eventbus.MessageEvent;
import net.xo68.destiny.manager.entity.JobInstanceExtend;
import net.xo68.destiny.manager.service.JobInstanceExtendService;
import net.xo68.destiny.manager.service.JobInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 工作节点任务状态上报事件处理
 * @author wuxie
 * @version 2020-11-25
 */
@Component
@Slf4j
public class JobStateReportEventHandle implements EventHandler<MessageEvent> {

    @Autowired
    private DatagramSerializer datagramSerializer;
    @Autowired
    private JobInstanceService jobInstanceService;
    @Autowired
    private JobInstanceExtendService jobInstanceExtendService;


    @Override
    public void onEvent(MessageEvent messageEvent, long l, boolean b) throws Exception {
        if(messageEvent.getBody()!=null){
            //log.debug("job state report:{}",messageEvent.getBody());
            try{
                final List<JobHandleReplyDatagram> replyDatagramList= (List<JobHandleReplyDatagram>) messageEvent.getBody();
                replyDatagramList.forEach(replyDatagram -> {
                    //log.debug("datagram: {}",replyDatagram);
                    replyDatagramHandle(replyDatagram);
                });
            }catch (Exception e){
                log.error("任务状态上报的消息报文类型异常,{}", messageEvent.getBody());
            }

        }else {
            log.error("事件消息体为空");
        }
    }

    /**
     * 回复报文处理
     * @param replyDatagram
     */
    private void replyDatagramHandle(final JobHandleReplyDatagram replyDatagram){
//        if(StringUtils.isNotBlank(replyDatagram.getDatagramClass()) && StringUtils.isNotBlank(replyDatagram.getDatagram())){
//            if(String.class.getName().equals(replyDatagram.getDatagramClass())){
//                String str=datagramSerializer.deserialize(replyDatagram.getDatagram());
//                log.debug("datagram body: {}", str);
//            }
//        }
        switch (replyDatagram.getPhase()){
            case START:
                jobInstanceService.handleStart(replyDatagram.getInstanceId(),replyDatagram.getStart());
                break;
            case RUNNING:
                break;
            case FINISH:
                Byte state= replyDatagram.getState()== JobHandleStateEnum.SUCCESS ? JobInstanceStateEnum.HANDLE_SUCCESS.getCode() : JobInstanceStateEnum.HANDLE_FAIL.getCode();
                jobInstanceService.handleFinish(replyDatagram.getInstanceId(),state,replyDatagram.getEnd());
                String datagram=datagramSerializer.decode(replyDatagram.getDatagram());
                jobInstanceExtendService.delete(replyDatagram.getInstanceId(), JobInstanceExtendEnum.HANDLE_RESULT.name());
                JobInstanceExtend instanceExtend=new JobInstanceExtend();
                instanceExtend.setInstanceId(replyDatagram.getInstanceId());
                instanceExtend.setExtKey(JobInstanceExtendEnum.HANDLE_RESULT.name());
                instanceExtend.setExtValue(datagram);
                jobInstanceExtendService.insert(instanceExtend);
                break;
        }
    }
}
